package LeetCode;

import java.util.HashMap;

/**
 * @Author: Dijah
 * @Date: 2023/1/11 17:37
 * @Desc: 无重复最长子串
 */
public class code3_lengthOfLongestSubstring {

    public static int lengthOfLongestSubstring(String s) {
        //滑动窗口
        int left = 0;
        int right = 0;
        //记录位置的
        HashMap<Character,Integer> map = new HashMap<>();
        HashMap<Character,Integer> newMap = new HashMap<>();
        char[] chars = s.toCharArray();
        while(right < s.length()){
            //右边界右移，扩大窗口
            //拿到右边界当前的位置
            Character c = chars[right];
            //放到map中，
            map.put(c,right);
            newMap.put(c,1);
            right++;
            if(newMap.get(c) > 1){
                //如果map中已经有了这个字符，那么left++,right++，
                //移除 map
                newMap.put(c,map.get(c) +1);
                // left 来打 c + 1 的位置，right++
                int cur = map.get(c);//当前map重复的字符的位置的索引
                left = cur + 1;
                right++;
            }
        }
        return map.size();
    }

    public static int lengthOfLongestSubstring1(String s){
        HashMap<Character,Integer> window = new HashMap<>();
        int left = 0;
        int right = 0;
        int res = 0;
        char[] chars = s.toCharArray();
        while (right < s.length()){
            char c = chars[right];
            right++;
            window.put(c,window.getOrDefault(c,0)+1);
            while (window.get(c) > 1){
                //如果有多个，说明需要缩小窗口
                char d = chars[left];
                left++;
                window.put(d,window.get(d)-1);

            }
            res = Math.max(res,right - left);
        }
        return res;
    }

    public static void main(String[] args) {
        String s = "pwwkew";
        System.out.println(lengthOfLongestSubstring1(s));
        System.out.println(lengthOfLongestSubstring(s));
    }
}
